﻿//Created by Action Script Viewer - http://www.buraks.com/asv
package Classes {
    import Engine.Classes.*;
    import flash.events.*;
    import Engine.Events.*;
    import Engine.Managers.*;
    import flash.display.*;
    import flash.geom.*;
    import Engine.Helpers.*;
    import Engine.Init.*;
    import Events.*;
    import flash.utils.*;
    import Transactions.*;
    import Classes.util.*;
    import Classes.sim.*;
    import __AS3__.vec.*;
    import com.greensock.*;
    import Modules.quest.Managers.*;
    import Display.*;
    import Classes.virals.*;
    import GameMode.*;
    import Display.CollectionsUI.*;
    import Modules.stats.data.*;
    import Classes.orders.*;
    import Classes.doobers.*;
    import flash.text.*;
    import Modules.stats.*;
    import Engine.*;
    import Modules.stats.trackers.*;
    import com.adobe.utils.*;

    public class GameWorld extends World implements IStatsTarget {

        private static const GAME_INIT_INCOMPLETE:uint = 0;
        private static const GAME_INIT_COMPLETE:uint = 1;
        public static const DEFCON_LEVEL1:int = 0;
        public static const DEFCON_LEVEL2:int = 1;
        public static const DEFCON_LEVEL3:int = 2;
        public static const DEFCON_LEVEL4:int = 3;
        public static const DEFCON_LOWEST_LEVEL:int = 0;
        private static const FPS_DEFCON_DOWN_THRESHOLD:int = 25;
        public static const DEFCON_HIGHEST_LEVEL:int = 3;
        private static const FPS_DEFCON_UP_THRESHOLD:int = 15;
        private static const FPS_UPDATE_INTERVAL:Number = 1000;
        private static const PERF_PROBABILITY:int = 10000;
        private static const OVERRIDE_LAYER_NAME:String = "default";
        private static const PERF_UPDATE_INTERVAL:Number = 5000;
        private static const SEC_ABOVE_DEFCON_THRESHOLD:int = 15;
        private static const SEC_BELOW_DEFCON_THRESHOLD:int = 10;
        public static const CITY_SAM_OWNER_ID:String = "-1";
        public static const CULL_ZOOM_IN:int = 0;
        public static const CULL_ZOOM_OUT:int = 1;
        public static const CULL_CHECK_ALL:int = 2;
        private static const RIVER_TILE_SCALE:Number = 1.25;

        private static var idleDelayFromSettings:Number = Global.gameSettings.getNumber("idleMissionTime");
        private static var giftDelayFromSettings:Number = Global.gameSettings.getNumber("giftMissionTime");
        private static var addNeighborDelayFromSettings:Number = Global.gameSettings.getNumber("addNeighborTime");

        public const GIFTBOX_ID:int = -1;
        public const INVENTORY_ID:int = -2;
        protected const UP:Vector2;
        protected const RIGHT:Vector2;
        protected const DOWN:Vector2;
        protected const LEFT:Vector2;

        private var m_gameInitStatus:uint = 0;
        protected var m_ownerId:String = null;
        public var lotOutlineColor:Number = 3829545;
        protected var m_activeModes:Array;
        protected var m_lotSprite:Sprite = null;
        protected var m_modeLock:int = 0;
        protected var m_neighborText:Array;
        protected var m_pendingVisitUserId:String;
        private var m_currentDefconLevel:int = 0;
        private var m_frameCount:int;
        private var m_giftRange:int;
        public var mostFrequentHelpers:Object;
        public var vistorCenterText:String;
        private var m_hasSeenGenericAd:Boolean = false;
        private var m_isAddNeighborShown:Boolean;
        private var m_lastAddNeighborTime:int;
        private var m_lastGenericAdTime:int;
        private var m_lastGiftMissionTime:int;
        private var m_lastIdleMissionTime:int;
        private var m_ownedCells:Array;
        public var m_territory:TerritoryMap;
        protected var m_wildernessSim:WildernessSim;
        private var m_lastPromoShowTime:Number = -1;
        private var m_lastUpdateTime:Number = 0;
        private var m_lastUpdate:int;
        private var m_promoDelay:Number = -1;
        private var m_scrollTween:TweenLite;
        private var m_zoomTween:TweenLite;
        private var m_secondsAboveDefconThreshold:int = 0;
        private var m_secondsBelowDefconThreshold:int = 0;
        private var m_showingGiftMissionDialog:Boolean = false;
        private var m_zoomEnabled:Boolean = true;
        private var m_unlockingMove:Boolean = false;
        protected var m_citySim:CitySim;
        protected var m_stateObservers:Array;
        protected var m_river:WaterFeature;
        private var m_grassBitmap:Bitmap = null;
        private var m_grassBitmapInitialized:Boolean = false;
        private var m_groundmapOrigin:Point;
        private var m_groundmapScale:Number;
        private var m_initialRoadsRect:Rectangle;
        protected var m_overlayBackgroundRect:Rectangle;
        protected var m_backgroundLoader:Loader;
        private var m_backgroundSprite:Sprite;
        protected var m_dooberManager:DooberManager;
        protected var m_orderManager:OrderManager;
        protected var m_viralManager:ViralManager;
        protected var m_currentThemes:Vector.<Theme>;
        protected var m_currentThemeCollections:Vector.<String>;
        protected var m_printPerformanceData:Boolean = false;
        private var m_alignSprite:Sprite;

        public function GameWorld():void{
            this.m_activeModes = [];
            this.m_neighborText = [];
            this.UP = new Vector2(0, 1);
            this.RIGHT = new Vector2(1, 0);
            this.DOWN = new Vector2(0, -1);
            this.LEFT = new Vector2(-1, 0);
            this.m_stateObservers = [];
            var _local1:Number = Global.gameSettings.getInt("farmSize", 80);
            super(_local1, _local1);
            this.m_citySim = new CitySim(this);
            this.m_dooberManager = new DooberManager(this);
            this.m_orderManager = new OrderManager();
            this.m_viralManager = new ViralManager();
            this.m_currentThemes = new Vector.<Theme>();
            this.m_currentThemeCollections = new Vector.<String>();
            this.m_lastUpdate = getTimer();
            this.m_frameCount = 0;
        }
        public function get gameInitStatus():uint{
            return (this.m_gameInitStatus);
        }
        public function set gameInitStatus(_arg1:uint):void{
            this.m_gameInitStatus = _arg1;
        }
        public function get overlayBackgroundRect():Rectangle{
            return (this.m_overlayBackgroundRect);
        }
        public function get wildernessSim():WildernessSim{
            return (this.m_wildernessSim);
        }
        public function get orderMgr():OrderManager{
            return (this.m_orderManager);
        }
        public function get viralMgr():ViralManager{
            return (this.m_viralManager);
        }
        public function get defCon():int{
            return (this.m_currentDefconLevel);
        }
        public function addObserver(_arg1:IGameWorldStateObserver):void{
            if (!ArrayUtil.arrayContainsValue(this.m_stateObservers, _arg1)){
                this.m_stateObservers.push(_arg1);
            };
        }
        public function removeObserver(_arg1:IGameWorldStateObserver):void{
            ArrayUtil.removeValueFromArray(this.m_stateObservers, _arg1);
        }
        public function get citySim():CitySim{
            return (this.m_citySim);
        }
        public function get dooberManager():DooberManager{
            return (this.m_dooberManager);
        }
        public function get river():WaterFeature{
            return (this.m_river);
        }
        public function get isEditMode():Boolean{
            var _local1:GameMode = this.getTopGameMode();
            return (((!((_local1 == null))) && (_local1.supportsEditing)));
        }
        public function get isUnlockingMove():Boolean{
            return (this.m_unlockingMove);
        }
        public function set isUnlockingMove(_arg1:Boolean):void{
            this.m_unlockingMove = _arg1;
        }
        public function enableZoom(_arg1:Boolean):void{
            this.m_zoomEnabled = _arg1;
        }
        public function isZoomEnabled():Boolean{
            return (this.m_zoomEnabled);
        }
        public function set printPerformanceData(_arg1:Boolean):void{
            this.m_printPerformanceData = _arg1;
        }
        public function getStatsCounterObject():Vector.<StatsCountData>{
            var _local1:Vector.<StatsCountData> = new Vector.<StatsCountData>();
            var _local2:Array = this.getObjectsByTypes([WorldObjectTypes.BUSINESS]);
            var _local3:Array = this.getObjectsByTypes([WorldObjectTypes.RESIDENCE]);
            var _local4:Array = this.getObjectsByTypes([WorldObjectTypes.MUNICIPAL]);
            var _local5:Array = this.getObjectsByTypes([WorldObjectTypes.LANDMARK]);
            var _local6:Array = this.getObjectsByTypes([WorldObjectTypes.PLOT]);
            var _local7:Array = this.getObjectsByTypes([WorldObjectTypes.SIDEWALK]);
            var _local8:Array = this.getObjectsByTypes([WorldObjectTypes.ROAD]);
            var _local9:Array = this.getObjectsByTypes([WorldObjectTypes.DECORATION]);
            var _local10:int = Global.player.expansionsPurchased;
            var _local11:Array = this.getObjectsByTypes([WorldObjectTypes.SHIP]);
            _local1.push(new StatsCountData(new StatsOntology("num_businesses"), _local2.length));
            _local1.push(new StatsCountData(new StatsOntology("num_residences"), _local3.length));
            _local1.push(new StatsCountData(new StatsOntology("num_municipals"), _local4.length));
            _local1.push(new StatsCountData(new StatsOntology("num_plots"), _local6.length));
            _local1.push(new StatsCountData(new StatsOntology("num_sidewalks"), _local7.length));
            _local1.push(new StatsCountData(new StatsOntology("num_roads"), _local8.length));
            _local1.push(new StatsCountData(new StatsOntology("num_decorations"), _local9.length));
            _local1.push(new StatsCountData(new StatsOntology("num_landmarks"), _local5.length));
            _local1.push(new StatsCountData(new StatsOntology("num_ships"), _local11.length));
            _local1.push(new StatsCountData(new StatsOntology("num_expansions"), _local10));
            return (_local1);
        }
        public function addGameMode(_arg1:GameMode, _arg2:Boolean=true):void{
            var _local3:String;
            var _local4:int;
            var _local5:GameMode;
            if (this.isModeLocked() == false){
                _local3 = getQualifiedClassName(_arg1);
                _local4 = 0;
                while (_local4 < this.m_activeModes.length) {
                    _local5 = (this.m_activeModes[_local4] as GameMode);
                    _local5.disableMode();
                    if (_arg2){
                        _local5.removeMode();
                    };
                    if (getQualifiedClassName(_local5) == _local3){
                        this.m_activeModes.splice(_local4, 1);
                        _local4--;
                    };
                    _local4++;
                };
                if (_arg2){
                    this.m_activeModes = new Array(_arg1);
                } else {
                    this.m_activeModes.push(_arg1);
                };
                if (_arg2){
                    UI.removeAllCursors();
                };
                _arg1.enableMode();
            };
        }
        public function centerCityView(_arg1:Number=1):void{
            var _local2:int = Global.gameSettings.getInt("startCameraX");
            var _local3:int = Global.gameSettings.getInt("startCameraY");
            this.centerOnIsoPosition(new Vector3(_local2, _local3), _arg1);
        }
        override public function centerOnObject(_arg1:WorldObject, _arg2:Number=1):void{
            var _local3:Vector3 = _arg1.getPosition();
            this.centerOnIsoPosition(_local3, _arg2);
        }
        public function centerOnIsoPosition(_arg1:Vector3, _arg2:Number=1):void{
            if (this.m_scrollTween){
                this.m_scrollTween.complete(true);
                this.m_scrollTween = null;
            };
            var _local3:Object = {
                startPos:GlobalEngine.viewport.getScrollPosition(),
                alpha:0
            };
            var _local4:IsoViewport = (GlobalEngine.viewport as IsoViewport);
            _local4.centerOnTilePos(_arg1.x, _arg1.y);
            _local3.endPos = _local4.getScrollPosition();
            _local4.setScrollPosition(_local3.startPos);
            this.m_scrollTween = TweenLite.to(_local3, _arg2, {
                alpha:1,
                onUpdate:this.onUpdateScrollTween,
                onUpdateParams:[_local3],
                onComplete:this.onCompleteScrollTween
            });
        }
        public function zoom(_arg1:Number, _arg2:Number, _arg3:Number=1):void{
            if (this.m_zoomTween){
                this.m_zoomTween.complete(true);
                this.m_zoomTween = null;
            };
            var _local4:IsoViewport = (GlobalEngine.viewport as IsoViewport);
            _local4.setZoom(_arg1);
            var _local5:Object = {
                startZoom:_arg1,
                alpha:0
            };
            _local5.endZoom = _arg2;
            this.m_zoomTween = TweenLite.to(_local5, _arg3, {
                alpha:1,
                onUpdate:this.onUpdateZoomTween,
                onUpdateParams:[_local5],
                onComplete:this.onCompleteZoomTween
            });
        }
        public function zoomFinished():Boolean{
            if (((this.m_zoomTween) && (this.m_zoomTween.active))){
                return (false);
            };
            if (((this.m_scrollTween) && (this.m_scrollTween.active))){
                return (false);
            };
            return (true);
        }
        protected function onCompleteZoomTween():void{
            this.m_zoomTween = null;
        }
        protected function onUpdateZoomTween(_arg1:Object):void{
            var _local2:Number = ((_arg1.endZoom * _arg1.alpha) + (_arg1.startZoom * (1 - _arg1.alpha)));
            GlobalEngine.viewport.setZoom(_local2);
        }
        override public function cleanUp():void{
            var _local1:IGameWorldStateObserver;
            for each (_local1 in this.m_stateObservers) {
                _local1.cleanUp();
            };
            while (this.m_activeModes.length) {
                this.popGameMode();
            };
			// 清理主地图界面
            if (((!((this.m_lotSprite == null))) && (!((this.m_lotSprite.parent == null))))){
                this.m_lotSprite.parent.removeChild(this.m_lotSprite);
                this.m_lotSprite = null;
            };
			// 清理界面的tip
            Global.ui.cleanUpToolTip();
			// 清理各个层
            super.cleanUp();
        }
        public function getActiveGameModes():Array{
            return (this.m_activeModes);
        }
        public function getObjectsByNames(_arg1:Array):Array{
            var _local5:MapResource;
            var _local6:String;
            var _local7:int;
            var _local2:Array = new Array();
            var _local3:Array = getObjects();
            var _local4:int;
            while (_local4 < _local3.length) {
                _local5 = (_local3[_local4] as MapResource);
                if (((!((_local5 == null))) && (!((_local5.getItem() == null))))){
                    _local6 = _local5.getItem().name;
                    _local7 = 0;
                    while (_local7 < _arg1.length) {
                        if (_local6 == _arg1[_local7]){
                            _local2.push(_local5);
                        };
                        _local7++;
                    };
                };
                _local4++;
            };
            return (_local2);
        }
        public function getObjectsByTypes(_arg1:Array):Array{
            var _local5:MapResource;
            var _local6:int;
            var _local7:int;
            var _local8:int;
            var _local2:Array = new Array();
            var _local3:Array = getObjects();
            var _local4:int;
            while (_local4 < _local3.length) {
                _local5 = (_local3[_local4] as MapResource);
                if (((!((_local5 == null))) && (!((_local5.getItem() == null))))){
                    _local6 = _local5.getObjectType();
                    _local7 = 0;
                    while (_local7 < _arg1.length) {
                        _local8 = _arg1[_local7];
                        if (_local6 == _local8){
                            _local2.push(_local5);
                        };
                        _local7++;
                    };
                };
                _local4++;
            };
            return (_local2);
        }
        public function getObjectsByClassAt(_arg1:Class, _arg2:Vector3):Array{
            var _local5:WorldObject;
            var _local3:Array = new Array();
            if (((!(_arg1)) || (!(_arg2)))){
                return (_local3);
            };
            var _local4:Array = Global.world.getCollisionMap().getObjectsByPosition(_arg2.x, _arg2.y);
            for each (_local5 in _local4) {
                if ((_local5 is _arg1)){
                    _local3.push(_local5);
                };
            };
            return (_local3);
        }
        public function getObjectsByPredicate(_arg1:Function):Array{
            var _local3:ObjectLayer;
            var _local4:WorldObject;
            var _local2:Array = [];
            for each (_local3 in m_children) {
                for each (_local4 in _local3.children) {
                    if (_arg1(_local4)){
                        _local2.push(_local4);
                    };
                };
            };
            return (_local2);
        }
        public function getObjectsByKeywords(... _args):Array{
            var _local5:MapResource;
            var _local6:Boolean;
            var _local7:Item;
            var _local8:String;
            var _local2:Array = [];
            var _local3:Array = getObjects();
            var _local4:int;
            while (_local4 < _local3.length) {
                _local5 = (_local3[_local4] as MapResource);
                if (_local5){
                    _local6 = true;
                    _local7 = _local5.getItem();
                    for each (_local8 in _args) {
                        if (((!(_local7)) || (!(_local7.itemHasKeyword(_local8))))){
                            _local6 = false;
                            break;
                        };
                    };
                    if (_local6){
                        _local2.push(_local5);
                    };
                };
                _local4++;
            };
            return (_local2);
        }
        public function findConnectingMapResources(_arg1:int, _arg2:int, _arg3:int, _arg4:int, _arg5:Array=null, _arg6:Boolean=true, _arg7:Class=null):Array{
            var _local16:WorldObject;
            var _local17:Number;
            var _local18:Boolean;
            var _local19:WorldObject;
            var _local8:int = (_arg1 - 1);
            var _local9:int = ((_arg1 + _arg3) + 1);
            var _local10:int = (_arg2 - 1);
            var _local11:int = ((_arg2 + _arg4) + 1);
            var _local12:Array = [];
            var _local13:Object = {};
            var _local14:Array = [];
            var _local15:Boolean = Global.world.checkCollision((_local8 + 1), (_local11 - 1), (_local9 - 1), (_local11 - 1), [], _local14);
            _local12 = _local14.splice(0);
            if (((((!(_local15)) || (_arg6))) || (_arg7))){
                _local15 = Global.world.checkCollision((_local8 + 1), _local10, (_local9 - 1), _local10, [], _local14);
                _local12 = _local12.concat(_local14.splice(0));
            };
            if (((((!(_local15)) || (_arg6))) || (_arg7))){
                _local15 = Global.world.checkCollision(_local8, (_local10 + 1), _local8, (_local11 - 1), [], _local14);
                _local12 = _local12.concat(_local14.splice(0));
            };
            if (((((!(_local15)) || (_arg6))) || (_arg7))){
                _local15 = Global.world.checkCollision((_local9 - 1), (_local10 + 1), (_local9 - 1), (_local11 - 1), [], _local14);
                _local12 = _local12.concat(_local14.splice(0));
            };
            for each (_local16 in _local12) {
                _local17 = _local16.getId();
                _local13[_local17] = _local16;
            };
            _local12 = [];
            for each (_local16 in _local13) {
                if (((_arg5) && (_arg5.length))){
                    _local18 = false;
                    for each (_local19 in _arg5) {
                        if (_local19 == _local16){
                            _local18 = true;
                            break;
                        };
                    };
                    if (((!(_local18)) && (((!(_arg7)) || ((_local16 is _arg7)))))){
                        _local12[_local12.length] = _local16;
                    };
                } else {
                    if (((!(_arg7)) || ((_local16 is _arg7)))){
                        _local12[_local12.length] = _local16;
                    };
                };
            };
            return (_local12);
        }
        public function getTopGameMode():GameMode{
            var _local1:GameMode;
            if (this.m_activeModes.length){
                _local1 = this.m_activeModes[(this.m_activeModes.length - 1)];
            };
            return (_local1);
        }
        override public function initialize():void{
            var _local2:IGameWorldStateObserver;
            var _local3:Rectangle;
            this.setNumShards(1);
            super.initialize();
            this.m_lastUpdateTime = getTimer();
			
			// 合并可用地图区域和道路区域，初始化这两个区域的CollisionMap
            if (this.m_territory){
                _local3 = this.m_territory.occupiedBoundingRect;
                if (this.m_initialRoadsRect){
                    _local3 = _local3.union(this.m_initialRoadsRect);
                };
                m_collisionMap.dispose();
                m_collisionMap = new GameCollisionMap();
                (m_collisionMap as GameCollisionMap).initRect(_local3.x, _local3.y, _local3.width, _local3.height);
            };
			
			// 初始化几个图层
            if (Game.m_blitting){
                addLayer(new GameObjectLayer("road", -2));
                addLayer(new GameObjectLayer("backship", -1));
                addLayer(new GameObjectLayer("frontship", 1));
                addLayer(new GameObjectLayer("doober", 8));
                addLayer(new GameObjectLayer("clouds", 10));
            } else {
                addLayer(new RoadLayer("road", -2));
                addLayer(new ObjectLayer("backship", -1));
                addLayer(new ObjectLayer("frontship", 1));
                addLayer(new ObjectLayer("doober", 8));
                addLayer(new ObjectLayer("clouds", 10));
            };
			
            InitializationManager.getInstance().addEventListener(Event.COMPLETE, this.onGameInitComplete);
            this.setDefaultGameMode();
            if (GlobalEngine.socialNetwork){
                GlobalEngine.socialNetwork.addEventListener(SocialNetworkEvent.GET_FRIENDS_COMPLETE, this.onGetFriends);
            };
            if (this.m_lotSprite == null){
                this.createLotBG(true);
            };
            var _local1:int = Global.gameSettings.getNumber("giftMissionTimeRange");
            this.m_giftRange = Math.round((Math.random() * _local1));
            this.m_isAddNeighborShown = false;
            for each (_local2 in this.m_stateObservers) {
                _local2.initialize();
            };
            dispatchEvent(new Event(Event.COMPLETE));
        }

		
        private function createObjects(_arg1:Object):void{
            var _local3:String;
            var _local4:String;
            var _local5:Object;
            var _local6:WorldObject;
			// 清理界面和UI
            this.cleanUp();
			
			
            if (((_arg1.sizeX) && (_arg1.sizeY))){
                m_size.x = _arg1.sizeX;
                m_size.y = _arg1.sizeY;
            };
			
			// 合并道路的矩形
            var _local2:Rectangle = new Rectangle();
            this.m_initialRoadsRect = null;
            for (_local3 in _arg1.objects) {
                _local5 = _arg1.objects[_local3];
                if (_local5.className == "Road"){
                    _local2.x = _local5.position.x;
                    _local2.y = _local5.position.y;
                    _local2.width = Road.SIZE_X;
                    _local2.height = Road.SIZE_Y;
                    if (this.m_initialRoadsRect == null){
                        this.m_initialRoadsRect = _local2;
                    } else {
                        this.m_initialRoadsRect = this.m_initialRoadsRect.union(_local2);
                    };
                };
            };
			
			// 创建游戏界面的各个层
            this.initialize();
			
			// 创建放物品的这个层
            if (Game.m_blitting){
                m_defaultLayer = new GameObjectLayer(OVERRIDE_LAYER_NAME);
            } else {
                m_defaultLayer = new ObjectLayer(OVERRIDE_LAYER_NAME);
            };
            addLayer(m_defaultLayer);
            if (Game.m_blitting){
                addLayer(new GameObjectLayer("npc", 1));
            };
            for (_local4 in _arg1.objects) {
                _local6 = this.createObjectInstance(_arg1.objects[_local4]);
                if (_local6){
                    _local6.loadObject(_arg1.objects[_local4]);
                    _local6.setOuter(this);
                    _local6.attach();
                };
            };
        }
        public function isModeLocked():Boolean{
            return ((this.m_modeLock > 0));
        }
        private function createWaterFeatures(_arg1:Object):void{
            if (!_arg1.waterFeatures){
                return;
            };
            if (_arg1.waterFeatures.length < 1){
                return;
            };
            var _local2:WaterFeature = new WaterFeature();
            _local2.loadObject(_arg1.waterFeatures[0]);
            this.m_river = _local2;
        }
        protected function loadTerritory(_arg1:Object):void{
            var _local2:int;
            var _local3:Rectangle;
            if (((_arg1.mapRects) && (_arg1.mapRects.length))){
                this.m_territory = new TerritoryMap(12);
                _local2 = 0;
                while (_local2 < _arg1.mapRects.length) {
                    _local3 = new Rectangle(_arg1.mapRects[_local2].x, _arg1.mapRects[_local2].y, _arg1.mapRects[_local2].width, _arg1.mapRects[_local2].height);
                    this.m_territory.addTerritory(_local3);
                    _local2++;
                };
            };
        }
        public function rebuildCollisionMap():void{
            var _local2:ObjectLayer;
            var _local3:WorldObject;
            m_collisionMap.dispose();
            var _local1:Rectangle = this.m_territory.occupiedBoundingRect;
            if (this.m_initialRoadsRect){
                _local1 = _local1.union(this.m_initialRoadsRect);
            };
            (m_collisionMap as GameCollisionMap).initRect(_local1.x, _local1.y, _local1.width, _local1.height);
            (m_collisionMap as GameCollisionMap).setOwnedArea(this.m_territory.occupiedRects);
            for each (_local2 in m_children) {
                for each (_local3 in _local2.children) {
                    m_collisionMap.insertObject(_local3);
                };
            };
        }
        override public function loadObject(_arg1:Object):void{
            var _local4:IGameWorldStateObserver;
            this.m_ownerId = _arg1.ownerId;
            this.loadTerritory(_arg1);
			
			// 看着是处理皮肤相关的东西，不过目前没有什么用处
            this.populateThemes(_arg1.currentThemes, _arg1.currentThemeCollections);
			
			
            this.createObjects(_arg1);
			
			// 填充草地
            var _local2:Bitmap = new EmbeddedArt.grassTile();
            var _local3:TextureTile = new TextureTile();
            _local3.setBitmapData(_local2.bitmapData);
            m_terrain = new SingleTileTerrain(_local3, this.getGridWidth(), this.getGridHeight());
			
			// 跟河流相关的特征，目前还没有启用
            this.createWaterFeatures(_arg1);
			// 跟人口相关的特性
            this.citySim.loadObject(_arg1.citySim);
            m_tileMap.setTerrain(m_terrain);
            if (this.m_territory){
                (m_collisionMap as GameCollisionMap).setOwnedArea(this.m_territory.occupiedRects);
            };
            this.setDefaultGameMode();
            if (Global.isVisiting() == false){
                this.resetIdleMissionTime();
                this.resetLastPromoTime();
            };
			
			// 创建背景荒地的树、草以及
            if (this.m_wildernessSim == null){
                this.m_wildernessSim = new WildernessSim();
            } else {
                this.createOverlayBackground();
            };
            for each (_local4 in this.m_stateObservers) {
                _local4.onGameLoaded(_arg1);
            };
        }
        override public function insertObjectIntoDepthArray(_arg1:WorldObject, _arg2:String=null):void{
            var _local3:ObjectLayer = getObjectLayerByName(_arg2);
            if ((((_arg2 == null)) || ((_local3 == null)))){
                _arg2 = DEFAULT_LAYER_NAME;
            };
            super.insertObjectIntoDepthArray(_arg1, _arg2);
        }
        public function lockGameMode():void{
            this.m_modeLock++;
        }
        public function popGameMode():void{
            var _local1:GameMode;
            if (((this.m_activeModes.length) && ((this.isModeLocked() == false)))){
                _local1 = (this.m_activeModes.pop() as GameMode);
                _local1.disableMode();
                if (this.m_activeModes.length){
                    this.m_activeModes[(this.m_activeModes.length - 1)].enableMode();
                };
            };
        }
        public function removeGameMode(_arg1:GameMode):void{
            var _local2:int;
            var _local3:GameMode;
            if (((this.m_activeModes.length) && ((this.isModeLocked() == false)))){
                _local2 = 0;
                while (_local2 < this.m_activeModes.length) {
                    _local3 = (this.m_activeModes[_local2] as GameMode);
                    if (_local3 == _arg1){
                        _arg1.disableMode();
                        this.m_activeModes.splice(_local2, 1);
                        if ((((_local2 == this.m_activeModes.length)) && ((this.m_activeModes.length > 0)))){
                            this.m_activeModes[(this.m_activeModes.length - 1)].enableMode();
                        };
                        break;
                    };
                    _local2++;
                };
            };
        }
        override public function getObjectById(_arg1:int, _arg2:int=16777215):WorldObject{
            var _local3:ObjectLayer;
            var _local4:*;
            var _local5:WorldObject;
            for each (_local3 in m_children) {
                for each (_local4 in _local3.children) {
                    _local5 = (_local4 as WorldObject);
                    if (((((!((_local5 == null))) && ((_local5.getId() == _arg1)))) && (((_local5.getObjectType() & _arg2) > 0)))){
                        return (_local5);
                    };
                };
            };
            return (null);
        }
        public function resetAddNeighborTime():void{
            this.m_lastAddNeighborTime = getTimer();
        }
        public function resetGenericAdTime():void{
            this.m_lastGenericAdTime = getTimer();
        }
        public function resetGiftMissionTime():void{
            this.m_lastGiftMissionTime = getTimer();
        }
        public function resetIdleMissionTime():void{
            this.m_lastIdleMissionTime = getTimer();
        }
        public function resetLastPromoTime():void{
            this.m_lastPromoShowTime = GlobalEngine.getTimer();
        }
        public function isHome():Boolean{
            return ((((Global.isVisiting() == false)) && ((this.m_ownerId == GlobalEngine.socialNetwork.getLoggedInUserId()))));
        }
        public function get ownerId():String{
            return (this.m_ownerId);
        }
        public function get isOwnerCitySam():Boolean{
            var _local1:Boolean = Boolean((this.m_ownerId == CITY_SAM_OWNER_ID));
            return (_local1);
        }
        public function setDefaultGameMode():void{
            if (Global.isVisiting()){
                this.addGameMode(new GMVisit(Global.getVisiting()));
            } else {
                this.addGameMode(new GMPlay());
            };
        }
        public function isThemeEnabled(_arg1:String):Boolean{
            return ((this.m_currentThemes.indexOf(_arg1) >= 0));
        }
        public function isThemeCollectionEnabled(_arg1:Item):Boolean{
            return ((this.m_currentThemeCollections.indexOf(_arg1.name) >= 0));
        }
        public function get currentThemes():Vector.<Theme>{
            return (this.m_currentThemes);
        }
        private function convertCurrentThemes(_arg1:Array):Vector.<Theme>{
            var _local3:Theme;
            var _local2:Vector.<Theme> = new Vector.<Theme>();
            for each (_local3 in _arg1) {
                _local2.push(_local3);
            };
            return (_local2);
        }
        private function convertCurrentThemeCollections(_arg1:Array):Vector.<String>{
            var _local3:String;
            var _local2:Vector.<String> = new Vector.<String>();
            for each (_local3 in _arg1) {
                _local2.push(_local3);
            };
            return (_local2);
        }
        private function populateThemes(_arg1:Array, _arg2:Array):void{
            var _local3:String;
            var _local4:Item;
            var _local5:Vector.<Theme>;
            this.m_currentThemes = new Vector.<Theme>();
            this.m_currentThemeCollections = new Vector.<String>();
            this.m_currentThemeCollections = this.convertCurrentThemeCollections(_arg2);
            for each (_local3 in this.m_currentThemeCollections) {
                _local4 = Global.gameSettings.getItemByName(_local3);
                if (_local4){
                    _local5 = this.convertCurrentThemes(_local4.getThemeCollection());
                    this.insertThemes(_local5);
                };
            };
        }
        private function insertThemes(_arg1:Vector.<Theme>):void{
            var _local2:Theme;
            for each (_local2 in _arg1) {
                this.insertTheme(_local2);
            };
        }
        private function insertTheme(_arg1:Theme):void{
            var _local4:Theme;
            var _local2:int;
            var _local3:Boolean;
            for each (_local4 in this.m_currentThemes) {
                if (_local4.priority > _arg1.priority){
                    this.m_currentThemes.splice(_local2, 0, _arg1);
                    _local3 = true;
                    break;
                };
                _local2++;
            };
            if (!_local3){
                this.m_currentThemes.push(_arg1);
            };
        }
        public function reload():void{
            GameTransactionManager.addTransaction(new TWorldLoad(this.m_ownerId), true, true);
            TransactionManager.sendAllTransactions(true);
        }
        public function isDefaultGameMode():Boolean{
            var _local1:GameMode = this.getTopGameMode();
            var _local2:Boolean;
            if (Global.isVisiting()){
                _local2 = (_local1 is GMVisit);
            } else {
                _local2 = (_local1 is GMPlay);
            };
            return (_local2);
        }
        public function unlockGameMode():void{
            if (this.m_modeLock > 0){
                this.m_modeLock--;
            };
        }
        public function updateNeighborText():void{
            this.createLotBG(false);
        }
        override public function updateWorld():void{
            var _local3:IGameWorldStateObserver;
            var _local4:Quest;
            super.updateWorld();
            var _local1:int = getTimer();
            if (OptimizationConfig.enableDefCon){
                this.monitorPerformance(_local1);
            };
            IdleDialogManager.doIdleDialogTimerCheck();
            ViralManager.doViralManagerThawCheck();
            CloudManager.doTimerCheck();
            Global.player.update();
            if (this.m_wildernessSim){
                this.m_wildernessSim.update();
            };
            var _local2:Number = ((_local1 - this.m_lastUpdateTime) / 1000);
            for each (_local3 in this.m_stateObservers) {
                if ((_local3 is IGameWorldUpdateObserver)){
                    (_local3 as IGameWorldUpdateObserver).update(_local2);
                };
            };
            Global.ui.updateToolTip(_local2);
            Global.world.citySim.friendVisitManager.update(((_local1 - this.m_lastUpdateTime) / 1000));
            Global.guide.update();
            for each (_local4 in Global.questManager.getActiveQuests()) {
                if ((_local4 is GameQuest)){
                    (_local4 as GameQuest).updateGuide();
                };
            };
            Global.hud.streakBonus.onUpdate(_local2);
            CollectionPanelPopout.getInstance().onUpdate(_local2);
            this.m_lastUpdateTime = _local1;
        }
        public function getPickObjects(_arg1:Point, _arg2:uint=16777215, _arg3:uint=0):Array{
            var _local5:int;
            var _local6:ObjectLayer;
            var _local7:int;
            var _local8:PositionedObject;
            var _local9:PositionedObject;
            var _local10:Array;
            var _local11:int;
            var _local4:Array = [];
            _local5 = (m_children.length - 1);
            while (_local5 >= 0) {
                _local6 = (m_children[_local5] as ObjectLayer);
                _local9 = null;
                _local10 = _local6.children;
                _local11 = _local10.length;
                _local7 = (_local11 - 1);
                while (_local7 >= 0) {
                    _local8 = (_local10[_local7] as PositionedObject);
                    _local9 = (_local8.pickObject(_arg1, _arg2, _arg3) as PositionedObject);
                    if (_local9 != null){
                        _local4[_local4.length] = _local9;
                    };
                    _local7--;
                };
                _local5--;
            };
            return (_local4);
        }
        protected function checkPerformance(_arg1:int):void{
            if ((((DEFCON_LOWEST_LEVEL == this.m_currentDefconLevel)) && ((_arg1 <= FPS_DEFCON_UP_THRESHOLD)))){
                this.m_secondsBelowDefconThreshold++;
            } else {
                if ((((DEFCON_HIGHEST_LEVEL == this.m_currentDefconLevel)) && ((_arg1 > FPS_DEFCON_DOWN_THRESHOLD)))){
                    this.m_secondsAboveDefconThreshold++;
                } else {
                    if (((!((DEFCON_LOWEST_LEVEL == this.m_currentDefconLevel))) && (!((DEFCON_HIGHEST_LEVEL == this.m_currentDefconLevel))))){
                        if (_arg1 <= FPS_DEFCON_UP_THRESHOLD){
                            this.m_secondsBelowDefconThreshold++;
                            this.m_secondsAboveDefconThreshold = 0;
                        } else {
                            this.m_secondsAboveDefconThreshold++;
                            this.m_secondsBelowDefconThreshold = 0;
                        };
                    } else {
                        this.m_secondsAboveDefconThreshold = 0;
                        this.m_secondsBelowDefconThreshold = 0;
                    };
                };
            };
            if (this.m_secondsBelowDefconThreshold >= SEC_BELOW_DEFCON_THRESHOLD){
                this.toggleDefconLevel((this.m_currentDefconLevel + 1));
            } else {
                if (this.m_secondsAboveDefconThreshold >= SEC_ABOVE_DEFCON_THRESHOLD){
                    this.toggleDefconLevel((this.m_currentDefconLevel - 1));
                };
            };
        }
        public function logGetProfilingData(_arg1:int, _arg2:Boolean):Object{
            var _local9:WorldObject;
            var _local10:NPC;
            var _local11:MapResource;
            var _local12:Object;
            var _local3:Boolean = ((Config.DEBUG_MODE) && (this.m_printPerformanceData));
            if (((!(_local3)) && (!(_arg2)))){
                return (0);
            };
            var _local4:int;
            var _local5:int;
            var _local6:int;
            var _local7:int;
            if (!Global.world.getObjectLayerByName("default")){
                return (null);
            };
            var _local8:Array = Global.world.getObjectLayerByName("default").children;
            for each (_local9 in _local8) {
                if ((_local9 is NPC)){
                    _local10 = (_local9 as NPC);
                    _local4++;
                    if (_local10.isVisible()){
                        _local5++;
                    };
                } else {
                    if ((_local9 is MapResource)){
                        _local11 = (_local9 as MapResource);
                        _local6++;
                        if (_local11.isVisible()){
                            _local7++;
                        };
                    };
                };
            };
            if (_arg2){
                _local12 = new Object();
                _local12["npc"] = _local4;
                _local12["npcv"] = _local5;
                _local12["build"] = _local6;
                _local12["buildv"] = _local7;
                return (_local12);
            };
            return (null);
        }
        public function getProfilingGameState():Object{
            var _local1:Object = {};
            _local1["frozen"] = UI.isScreenFrozen();
            _local1["edit"] = (Global.world.getTopGameMode() is GMEdit);
            _local1["visit"] = Global.isVisiting();
            _local1["fullscreen"] = Utilities.isFullScreen();
            _local1["defcon"] = this.defCon;
            var _local2:String = (((((((((Utilities.isFullScreen()) ? "f" : "w" + "-") + (GlobalEngine.zaspManager.zaspIsGameActive()) ? "a" : "i") + "-") + (UI.isScreenFrozen()) ? "fr" : "no") + "-") + (Global.isVisiting()) ? "visit" : ((Global.world.getTopGameMode() is GMEdit)) ? "edit" : "none") + "-") + this.defCon);
            _local1["description"] = _local2;
            return (_local1);
        }
        protected function createTerritoryBG():void{
            var _local1:Rectangle;
            var _local2:Vector2;
            if (this.m_territory){
                if (this.m_lotSprite != null){
                    this.m_lotSprite.graphics.clear();
                    GlobalEngine.viewport.overlayBase.removeChild(this.m_lotSprite);
                } else {
                    this.m_lotSprite = new Sprite();
                };
                this.m_lotSprite.graphics.beginFill(0, 0.3);
                for each (_local1 in this.m_territory.occupiedRects) {
                    _local2 = IsoMath.tilePosToPixelPos(_local1.x, _local1.y);
                    this.m_lotSprite.graphics.moveTo(_local2.x, _local2.y);
                    _local2 = IsoMath.tilePosToPixelPos(_local1.x, (_local1.y + _local1.height));
                    this.m_lotSprite.graphics.lineTo(_local2.x, _local2.y);
                    _local2 = IsoMath.tilePosToPixelPos((_local1.x + _local1.width), (_local1.y + _local1.height));
                    this.m_lotSprite.graphics.lineTo(_local2.x, _local2.y);
                    _local2 = IsoMath.tilePosToPixelPos((_local1.x + _local1.width), _local1.y);
                    this.m_lotSprite.graphics.lineTo(_local2.x, _local2.y);
                    _local2 = IsoMath.tilePosToPixelPos(_local1.x, _local1.y);
                    this.m_lotSprite.graphics.lineTo(_local2.x, _local2.y);
                };
                this.m_lotSprite.graphics.drawRect(-10000, -10000, 20000, 20000);
                this.m_lotSprite.graphics.endFill();
                GlobalEngine.viewport.overlayBase.cacheAsBitmap = true;
                GlobalEngine.viewport.overlayBase.addChildAt(this.m_lotSprite, 1);
            };
        }
        public function drawAlignmentGrid(_arg1:GameObject):void{
            if (this.m_alignSprite != null){
                GlobalEngine.viewport.overlayBase.removeChild(this.m_alignSprite);
            };
            this.m_alignSprite = new Sprite();
            this.m_alignSprite.graphics.lineStyle(0.5, 0xFFFFFF);
            var _local2:Box3D = _arg1.getBoundingBox();
            var _local3:Vector2 = IsoMath.tilePosToPixelPos(_local2.x, _local2.y);
            var _local4:Vector2 = IsoMath.tilePosToPixelPos((_local2.x + _local2.width), _local2.y);
            var _local5:Vector2 = IsoMath.tilePosToPixelPos(_local2.x, (_local2.y + _local2.height));
            var _local6:Vector2 = IsoMath.tilePosToPixelPos((_local2.x + _local2.width), (_local2.y + _local2.height));
            this.m_alignSprite.graphics.moveTo(_local3.x, _local3.y);
            this.m_alignSprite.graphics.lineTo(_local4.x, _local4.y);
            this.m_alignSprite.graphics.lineTo(_local6.x, _local6.y);
            this.m_alignSprite.graphics.lineTo(_local5.x, _local5.y);
            this.m_alignSprite.graphics.lineTo(_local3.x, _local3.y);
            GlobalEngine.viewport.overlayBase.addChildAt(this.m_alignSprite, GlobalEngine.viewport.overlayBase.numChildren);
        }
        protected function createLotBG(_arg1:Boolean=true):void{
            var _local13:TextField;
            if (this.gameInitStatus == GAME_INIT_COMPLETE){
                this.createTerritoryBG();
            };
        }
        protected function renderLotLine(_arg1:Sprite, _arg2:Point, _arg3:Vector2, _arg4:uint, _arg5:Boolean):void{
            var _local6:Point = new Point(((_arg3.x * getGridHeight()) * 0.5), ((_arg3.y * getGridHeight()) * 0.5));
            var _local7:Point = _arg2.add(_local6);
            var _local8:Point = _arg2.subtract(_local6).subtract(_local6);
            var _local9:Point = _local8.subtract(_local6);
            var _local10:Number = 2;
            var _local11:Number = (_arg5) ? (Math.PI * (-26 / 180)) : (Math.PI * (26 / 180));
            var _local12:Matrix = new Matrix();
            _local12.createGradientBox(_local6.length, _local6.length, _local11, _local7.x, _local7.y);
            _arg1.graphics.lineStyle(_local10, _arg4, 0);
            _arg1.graphics.lineGradientStyle("linear", [_arg4, _arg4], [0, 100], [20, 235], _local12);
            _arg1.graphics.moveTo(_local7.x, _local7.y);
            _arg1.graphics.lineTo(_arg2.x, _arg2.y);
            _arg1.graphics.lineGradientStyle("linear", [_arg4, _arg4], [100, 100], [20, 235]);
            _arg1.graphics.lineTo(_local8.x, _local8.y);
            _local12.createGradientBox(_local6.length, _local6.length, _local11, _local8.x, _local8.y);
            _arg1.graphics.lineGradientStyle("linear", [_arg4, _arg4], [100, 0], [20, 235], _local12);
            _arg1.graphics.lineTo(_local9.x, _local9.y);
        }
        protected function renderLotText(_arg1:Point, _arg2:uint, _arg3:Boolean, _arg4:String=null):void{
        }
        protected function onNeighborTextClick(_arg1:MouseEvent):void{
        }
        public function loadObjectInstance(_arg1:Object):WorldObject{
            var className:* = null;
            var itemName:* = null;
            var SavedObjectClassType:* = null;
            var instance:* = null;
            var data:* = _arg1;
            try {
                className = data.className;
                itemName = data.itemName;
                SavedObjectClassType = (getDefinitionByName(("Classes." + className)) as Class);
                if (itemName != null){
                    instance = new SavedObjectClassType(itemName);
                } else {
                    instance = new (SavedObjectClassType)();
                };
            } catch(e:ReferenceError) {
                ErrorManager.addError(("Type is not found " + className), ErrorManager.ERROR_REMOTEOBJECT_FAULT);
            };
            return (instance);
        }
        override protected function createObjectInstance(_arg1:Object):WorldObject{
            return (this.loadObjectInstance(_arg1));
        }
        public function enableAnimations(_arg1:Boolean):void{
            Global.playAnimations = _arg1;
            var _local2:Array = Global.world.getObjects();
            var _local3:int;
            while (_local3 < _local2.length) {
                (_local2[_local3] as GameObject).conditionallyRedraw(true);
                _local3++;
            };
        }
        protected function getNeighborName(_arg1:int):String{
            var _local3:Player;
            var _local2:String;
            _arg1 = ((Global.player.neighbors.length - _arg1) - 1);
            if (((Global.player) && ((_arg1 >= 0)))){
                _local3 = Global.player.findFriendById(Global.player.neighbors[_arg1]);
                if (_local3){
                    _local2 = _local3.firstName;
                };
            };
            return (_local2);
        }
        protected function giftIdleMissionHandler(_arg1:GenericPopupEvent):void{
            var _local2 = (_arg1.button == GenericPopup.YES);
            if (_local2 == true){
                GlobalEngine.socialNetwork.redirect("gifts.php?ref=giftMissionDialog");
            };
            this.m_showingGiftMissionDialog = false;
        }
        protected function monitorPerformance(_arg1:int):void{
            this.m_frameCount++;
            if (_arg1 >= (this.m_lastUpdate + FPS_UPDATE_INTERVAL)){
                this.m_lastUpdate = _arg1;
                this.checkPerformance(this.m_frameCount);
                this.logGetProfilingData(this.m_frameCount, false);
                this.m_frameCount = 0;
            };
        }
        override protected function onCompleteScrollTween():void{
            this.m_scrollTween = null;
        }
        protected function onConfirmVisit(_arg1:GenericPopupEvent):void{
            if (_arg1.button == GenericPopup.YES){
                UI.visitNeighbor(this.m_pendingVisitUserId);
            };
        }
        protected function onGameInitComplete(_arg1:Event):void{
            var _local2:Boolean;
            this.gameInitStatus = GAME_INIT_COMPLETE;
            if (!Global.player.isNewPlayer){
                GameTransactionManager.addTransaction(new TAutoPopZMC(), true);
            } else {
                StartupSessionTracker.interactive();
            };
            if (Global.player.compensationFlag != Player.NOT_COMPENSATED){
                _local2 = ((Global.player.compensationFlag)==Player.COMPENSATED_GIFT_CARD) ? true : false;
                UI.displayCreditBasic(_local2);
            };
            this.createLotBG();
            Global.player.commodities.updateCapacities();
            Global.hud.updateCommodities();
            if (!Global.mission.missionType){
                Global.postInitActions.execute();
            };
        }
        protected function onGetFriends(_arg1:Event):void{
            this.updateNeighborText();
        }
        override protected function onUpdateScrollTween(_arg1:Object):void{
            var _local2:Vector2 = Vector2.lerp(_arg1.startPos, _arg1.endPos, _arg1.alpha);
            GlobalEngine.viewport.setScrollPosition(_local2);
        }
        public function forceDefcon(_arg1:int):void{
            this.toggleDefconLevel(_arg1);
            this.m_secondsAboveDefconThreshold = -360;
            this.m_secondsBelowDefconThreshold = -360;
        }
        protected function toggleDefconLevel(_arg1:int):void{
            this.m_secondsAboveDefconThreshold = 0;
            this.m_secondsBelowDefconThreshold = 0;
            if (((Global.guide) && (Global.guide.isActive()))){
                if (Global.playAnimations == false){
                    this.enableAnimations(true);
                };
                Global.stage.quality = StageQuality.HIGH;
            } else {
                if (_arg1 != this.m_currentDefconLevel){
                    this.m_currentDefconLevel = _arg1;
                    switch (_arg1){
                        case DEFCON_LEVEL1:
                            if (!Global.player.options.graphicsLowQuality){
                                Global.stage.quality = (Game.m_blitting) ? StageQuality.LOW : StageQuality.HIGH;
                            };
                            CloudManager.activated = true;
                            break;
                        case DEFCON_LEVEL2:
                            Global.stage.quality = StageQuality.LOW;
                            CloudManager.activated = false;
                            break;
                        case DEFCON_LEVEL3:
                            if (false == Global.playAnimations){
                                this.enableAnimations(true);
                            };
                            break;
                        case DEFCON_LEVEL4:
                            if (true == Global.playAnimations){
                                this.enableAnimations(false);
                            };
                            break;
                    };
                };
            };
        }
		
		
		/**
		 *	填充草地大背景
		 */
        private function allocateGrassBitmap():void{
            var _local1:XML = Global.gameSettings.getXML();
            var _local2:int = _local1.background.@minBound;
            var _local3:int = _local1.background.@maxBound;
            var _local4:uint = _local1.background.@bgColor;
            this.m_groundmapScale = (1 / Global.gameSettings.getNumber("maxZoom", 1));
            this.m_groundmapOrigin = IsoMath.tilePosToPixelPos(0, 0);
            if (this.m_overlayBackgroundRect == null){
                this.m_overlayBackgroundRect = new Rectangle();
            };
            this.m_overlayBackgroundRect.width = (_local3 - _local2);
            this.m_overlayBackgroundRect.height = (_local3 - _local2);
            this.m_overlayBackgroundRect.x = (this.m_groundmapOrigin.x - (this.m_overlayBackgroundRect.width / 2));
            this.m_overlayBackgroundRect.y = (this.m_groundmapOrigin.y - (this.m_overlayBackgroundRect.width / 2));
            this.m_grassBitmapInitialized = false;
            if (this.m_grassBitmap){
                this.m_grassBitmap.bitmapData.fillRect(new Rectangle(0, 0, this.m_grassBitmap.width, this.m_grassBitmap.height), _local4);
                return;
            };
            var _local5:Number = this.m_groundmapScale;
            var _local6:BitmapData = new BitmapData(((_local3 - _local2) * (1 / _local5)), ((_local3 - _local2) * (1 / _local5)), false, _local4);
            this.m_grassBitmap = new Bitmap(_local6, "auto", true);
        }
		
        public function tileInGroundmap(_arg1:int, _arg2:int):Boolean{
            if (this.m_grassBitmap == null){
                return (false);
            };
            var _local3:Point = IsoMath.tilePosToPixelPos((_arg1 + 0.5), (_arg2 + 0.5));
            _local3.x = (_local3.x - this.m_groundmapOrigin.x);
            _local3.y = (_local3.y - this.m_groundmapOrigin.y);
            var _local4 = 5;
            if (_local3.x > (((this.m_groundmapScale * this.m_grassBitmap.bitmapData.width) / 2) - _local4)){
                return (false);
            };
            if (_local3.y > (((this.m_groundmapScale * this.m_grassBitmap.bitmapData.height) / 2) - _local4)){
                return (false);
            };
            if (_local3.x < -((((this.m_groundmapScale * this.m_grassBitmap.bitmapData.width) / 2) - _local4))){
                return (false);
            };
            if (_local3.y < -((((this.m_groundmapScale * this.m_grassBitmap.bitmapData.height) / 2) - _local4))){
                return (false);
            };
            return (true);
        }
        public function createOverlayBackground():void{
            var images:* = null;
            var items:* = null;
            var states:* = null;
            var initialized:* = false;
            var layer:* = null;
            var targetItem:* = null;
            var targetState:* = null;
			
			// 填充草地的大背景
            this.allocateGrassBitmap();
			// 添加野草和树到草地上
            this.m_wildernessSim.generateWilderness();
			
			// 把河流等其他背景填充上
            var xml:* = Global.gameSettings.getXML();
            var loaders:* = new Array();
            images = new Array();
            items = new Array();
            states = new Array();
            initialized = false;
            var i:* = 0;
            var cachedCount:* = 0;
            for each (layer in xml.background.layer) {
                targetItem = Global.gameSettings.getItemByName(layer.item.@name);
                items[i] = targetItem;
                targetState = layer.item.@state;
                states[i] = targetState;
                if (this.addBitmapToArray(targetItem, targetState, images, i)){
                    cachedCount = (cachedCount + 1);
                } else {
                    targetItem.addEventListener(LoaderEvent.LOADED, function (_arg1:Event):void{
                        var _local3:Item;
                        var _local2:int;
                        for each (_local3 in items) {
                            if (_local3.getCachedImage(states[_local2]) == null){
                                return;
                            };
                            addBitmapToArray(_local3, states[_local2], images, _local2);
                            _local2++;
                        };
                        if (!initialized){
                            grassitize(images);
                        };
                        initialized = true;
                    });
                };
                i = (i + 1);
            };
            if (cachedCount == i){
                if (!initialized){
                    this.grassitize(images);
                };
                initialized = true;
            };
        }
        private function addBitmapToArray(_arg1:Item, _arg2:String, _arg3:Array, _arg4:int):Boolean{
            var _local7:MovieClip;
            var _local8:int;
            var _local9:Bitmap;
            var _local5:Boolean;
            var _local6:ItemImageInstance = _arg1.getCachedImage(_arg2);
            if (_local6){
                if ((_local6.image is Bitmap)){
                    _arg3[_arg4] = (_local6.image as Bitmap);
                    return (true);
                };
                _local7 = (_local6.image as MovieClip);
                _local8 = 0;
                while (_local8 < _local7.numChildren) {
                    _local9 = (_local7.getChildAt(_local8) as Bitmap);
                    if (_local9){
                        _arg3[_arg4] = _local9;
                        _local5 = true;
                        break;
                    };
                    _local8++;
                };
            };
            return (_local5);
        }
        public function canDrawInGrass():Boolean{
            return (((!((this.m_grassBitmap == null))) && (this.m_grassBitmapInitialized)));
        }
        public function drawInGrass(_arg1:Bitmap, _arg2:Number, _arg3:Number, _arg4:int=0, _arg5:int=0):void{
            if (this.m_grassBitmap == null){
                return;
            };
            var _local6:Point = IsoMath.tilePosToPixelPos(0, 0);
            var _local7:int = _local6.x;
            var _local8:int = _local6.y;
            _local6 = IsoMath.tilePosToPixelPos(_arg2, _arg3);
            _local7 = (_local6.x - _local7);
            _local8 = (_local6.y - _local8);
            _local7 = (_local7 + _arg4);
            _local8 = (_local8 + _arg5);
            var _local9:Point = new Point();
            _local9.x = ((4 * _local7) + (this.m_grassBitmap.bitmapData.width * 0.5));
            _local9.y = ((4 * _local8) + (this.m_grassBitmap.bitmapData.width * 0.5));
            var _local10:Rectangle = new Rectangle(_arg2, _arg3, 2, 2);
            if (Global.world.rectInTerritory(_local10) == false){
                this.m_grassBitmap.bitmapData.copyPixels(_arg1.bitmapData, new Rectangle(0, 0, _arg1.width, _arg1.height), _local9);
            };
        }
        private function tileRivers(_arg1:BitmapData, _arg2:Bitmap, _arg3:XML):void{
            var _local4:Matrix = new Matrix();
            var _local5:Number = RIVER_TILE_SCALE;
            var _local6:int = _arg3.x;
            var _local7:int = _arg3.y;
            _local4.identity();
            _local4.translate(_local6, _local7);
            _local4.scale(_local5, _local5);
            _local4.translate((_arg1.width * 0.5), (_arg1.height * 0.5));
            _arg1.draw(_arg2.bitmapData, _local4);
        }
        private function tileOpenWater(_arg1:BitmapData, _arg2:Bitmap, _arg3:Bitmap, _arg4:XML, _arg5:int):void{
            var _local15:Number;
            var _local16:Number;
            var _local17:Number;
            var _local18:Number;
            var _local6:Matrix = new Matrix();
            var _local7:Number = RIVER_TILE_SCALE;
            var _local8:int = _arg4.x;
            var _local9:int = _arg4.y;
            var _local10:int = _arg4.fillBeneath;
            var _local11:int = _arg4.leftOverlap;
            var _local12:int = _arg4.rightOverlap;
            var _local13:int = _arg4.topOverlap;
            var _local14:int = _arg4.bottomOverlap;
            if (((_arg3) && (!((_local10 == 0))))){
                _local6.identity();
                _local9 = (_local9 + (_arg2.bitmapData.height - _local13));
                if (_arg5 > (_local9 * _local7)){
                    _local15 = (_arg5 - (_local9 * _local7));
                    _local15 = (_local15 + _local14);
                    _local16 = (_arg2.bitmapData.width * _local7);
                    if (_arg4.fillWidth != 0){
                        _local16 = (_arg4.fillWidth * _local7);
                    };
                    _local16 = (_local16 + (_local11 + _local12));
                    _local8 = (_local8 - _local11);
                    _local17 = (_local16 / _arg3.bitmapData.width);
                    _local18 = (_local15 / _arg3.bitmapData.height);
                    _local6.scale(_local17, _local18);
                    _local6.translate((_local8 * _local7), (_local9 * _local7));
                    _local6.translate((_arg1.width * 0.5), (_arg1.height * 0.5));
                    _arg1.draw(_arg3.bitmapData, _local6);
                };
            };
        }
        private function placeRiverTiles(_arg1:Array, _arg2:int, _arg3:XMLList, _arg4:BitmapData):void{
            var _local5:Bitmap;
            var _local8:XML;
            var _local9:int;
            var _local10:Bitmap;
            var _local6:int;
            var _local7:int;
            for each (_local8 in _arg3) {
                if (_local7 < _arg2){
                    _local7++;
                } else {
                    _local9 = _local8.isWaterTile;
                    _local10 = (_arg1[_local7] as Bitmap);
                    _local7++;
                    if (_local9){
                        _local6 = _local8.tileYLimit;
                        _local5 = _local10;
                    } else {
                        this.tileOpenWater(_arg4, _local10, _local5, _local8, _local6);
                    };
                };
            };
            _local7 = 0;
            for each (_local8 in _arg3) {
                if (_local7 < _arg2){
                    _local7++;
                } else {
                    _local9 = _local8.isWaterTile;
                    _local10 = (_arg1[_local7] as Bitmap);
                    _local7++;
                    if (_local9){
                    } else {
                        this.tileRivers(_arg4, _local10, _local8);
                    };
                };
            };
        }
        private function grassitize(_arg1:Array):void{
            var _local9:XML;
            var _local10:Bitmap;
            var _local11:Matrix;
            var _local12:Rectangle;
            var _local13:int;
            var _local14:int;
            var _local15:int;
            var _local16:int;
            var _local17:int;
            var _local18:int;
            var _local19:int;
            GameUtil.srand(0);
            var _local2:XML = Global.gameSettings.getXML();
            var _local3:Matrix = new Matrix();
            var _local4:Number = this.m_groundmapScale;
            _local3.scale(_local4, _local4);
            var _local5:BitmapData = this.m_grassBitmap.bitmapData;
            var _local6:uint = _local2.background.@bgColor;
            this.m_grassBitmap.bitmapData.fillRect(this.m_grassBitmap.bitmapData.rect, _local6);
            var _local7:int;
            var _local8:Point = new Point();
            for each (_local9 in _local2.background.layer) {
                _local10 = (_arg1[_local7] as Bitmap);
                _local11 = new Matrix();
                _local12 = _local10.bitmapData.rect;
                _local13 = _local9.tile;
                _local14 = _local9.river;
				
				// 放水的图层
                if (_local14){
                    this.placeRiverTiles(_arg1, _local7, _local2.background.layer, _local5);
                    break;
                };
				
                if (_local13){
                    _local15 = (_local5.width / _local12.width);
                    _local16 = (_local5.height / _local12.height);
                    _local17 = 0;
                    while (_local17 <= _local15) {
                        _local18 = 0;
                        while (_local18 <= _local16) {
                            _local8.x = (_local17 * _local12.width);
                            _local8.y = (_local18 * _local12.height);
                            _local5.copyPixels(_local10.bitmapData, new Rectangle(0, 0, _local10.width, _local10.height), _local8);
                            _local18++;
                        };
                        _local17++;
                    };
                }
				
				else {
                    _local19 = 0;
                    while (_local19 < _local9.instances) {
                        _local8.x = GameUtil.rand(0, _local5.width);
                        _local8.y = GameUtil.rand(0, _local5.height);
                        _local5.copyPixels(_local10.bitmapData, new Rectangle(0, 0, _local10.width, _local10.height), _local8);
                        _local19++;
                    };
                };
                _local7++;
            };
            this.m_grassBitmap.transform.matrix = _local3;
            _local3.translate(((-(this.m_grassBitmap.width) / 2) + this.m_groundmapOrigin.x), ((-(this.m_grassBitmap.height) / 2) + this.m_groundmapOrigin.y));
            this.m_grassBitmap.transform.matrix = _local3;
            this.m_grassBitmapInitialized = true;
            if (this.m_grassBitmap.parent == null){
                GlobalEngine.viewport.overlayBase.addChildAt(this.m_grassBitmap, 0);
            };
        }
        public function rand(_arg1:Number, _arg2:Number=0):Number{
            return (((Math.random() * (_arg1 - _arg2)) + _arg2));
        }
        private function onAvatarFeedClosed():void{
            Global.startTutorial();
        }
        public function rectIntersectsTerritory(_arg1:Rectangle):Boolean{
            var _local4:Rectangle;
            var _local2:Boolean;
            var _local3:Vector.<Rectangle> = this.m_territory.occupiedRects;
            for each (_local4 in _local3) {
                if (_arg1.intersects(_local4)){
                    _local2 = true;
                    break;
                };
            };
            return (_local2);
        }
        public function rectInTerritory(_arg1:Rectangle):Boolean{
            var _local2:Boolean = this.m_territory.rectInTerritory(_arg1);
            return (_local2);
        }
        public function getWorldRect():Rectangle{
            var _local1:Rectangle;
            if (this.m_territory){
                _local1 = this.m_territory.occupiedBoundingRect;
            } else {
                _local1 = new Rectangle(0, 0, getGridWidth(), getGridHeight());
            };
            return (_local1);
        }
        public function expandMap(_arg1:Rectangle):void{
            this.m_territory.addTerritory(_arg1);
            this.rebuildCollisionMap();
            this.createTerritoryBG();
        }
        public function updateWorldObjectCulling(_arg1:int):void{
            var _local3:WorldObject;
            var _local2:Array = Global.world.getObjects();
            for each (_local3 in _local2) {
                if ((((_arg1 == CULL_ZOOM_IN)) && (!(_local3.isVisible())))){
                } else {
                    if ((((_arg1 == CULL_ZOOM_OUT)) && (_local3.isVisible()))){
                    } else {
                        _local3.updateCulling();
                    };
                };
            };
        }
        override public function getNumObjects():int{
            var _local2:ObjectLayer;
            var _local1:int;
            for each (_local2 in m_children) {
                _local1 = (_local1 + _local2.children.length);
            };
            return (_local1);
        }
        override public function getNumVisibleObjects():int{
            var _local2:ObjectLayer;
            var _local3:Array;
            var _local4:PositionedObject;
            var _local1:int;
            for each (_local2 in m_children) {
                _local3 = _local2.children;
                for each (_local4 in _local3) {
                    if (_local4.isVisible()){
                        _local1++;
                    };
                };
            };
            return (_local1);
        }
        public function onResourceChange(_arg1:MapResource, _arg2:Vector3, _arg3:Vector3):void{
            var _local4:IGameWorldStateObserver;
            for each (_local4 in this.m_stateObservers) {
                _local4.onResourceChange(_arg1, _arg2, _arg3);
            };
        }
        public function getLinkedObjects(_arg1:MapResource):Array{
            var _local2:Array = new Array();
            switch (_arg1.getObjectType()){
                case WorldObjectTypes.DOCK_HOUSE:
                    _local2 = _local2.concat(getObjectsByClass(Dock));
                    _local2 = _local2.concat(getObjectsByClass(HarvestableShip));
                    break;
            };
            return (_local2);
        }

    }
}//package Classes 
